package com.jdjc.gateway.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jdjc.gateway.entity.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局异常处理
 */
@Component
public class gatewayExceptionHandler implements ErrorWebExceptionHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();
        int code = 200;
        String message = "";
        if (throwable instanceof SaTokenException) {
            code = 401;
            message = "用户无权限";
        } else {
            code = 500;
            message = "系统繁忙";
        }
        // 创建一个包含错误代码和消息的失败结果对象
        Result result = Result.fail(code, message);

        // 将响应的 Content-Type 头设置为 application/json
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 返回一个 Mono，它将把 Result 对象作为 JSON 写入响应体
        return response.writeWith(Mono.fromSupplier(() -> {
            // 从响应中获取 DataBufferFactory 以创建数据缓冲区
            DataBufferFactory dataBufferFactory = response.bufferFactory();

            // 初始化一个字节数组来保存序列化的 JSON
            byte[] bytes = null;

            try {
                // 使用 ObjectMapper 将 Result 对象序列化为 JSON 字节
                bytes = objectMapper.writeValueAsBytes(result);
            } catch (JsonProcessingException e) {
                // 如果序列化对象时出错，将异常包装在 RuntimeException 中
                throw new RuntimeException(e);
            }

            // 将 JSON 字节包装在 DataBuffer 中并返回
            return dataBufferFactory.wrap(bytes);
        }));
    }
}
